package org.tis.tools.senior.module.developer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.tis.tools.core.utils.StringUtil;
import org.tis.tools.senior.module.core.config.SvnProperties;
import org.tis.tools.senior.module.developer.controller.request.HomePageShowEmphasisRequest;
import org.tis.tools.senior.module.developer.controller.request.RollBackAddRequest;
import org.tis.tools.senior.module.developer.controller.request.VerifyArtfRequest;
import org.tis.tools.senior.module.developer.controller.request.WorkitemAddAndUpdateRequest;
import org.tis.tools.senior.module.developer.dao.SWorkitemMapper;
import org.tis.tools.senior.module.developer.entity.*;
import org.tis.tools.senior.module.developer.entity.enums.*;
import org.tis.tools.senior.module.developer.entity.vo.*;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.*;
import org.tis.tools.senior.module.developer.util.DeveloperUtils;
import org.tmatesoft.svn.core.SVNException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * sWorkitem的Service接口实现类
 * 
 * @author Auto Generate Tools
 * @date 2018/06/20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SWorkitemServiceImpl extends ServiceImpl<SWorkitemMapper, SWorkitem> implements ISWorkitemService {

    @Autowired
    private ISBranchService branchService;

    @Autowired
    private ISBranchMappingService branchMappingService;

    @Autowired
    private ISDeliveryService deliveryService;

    @Autowired
    private ISSvnKitService svnKitService;

    @Autowired
    private ISProjectService projectService;

    @Autowired
    private SvnProperties svnProperties;

    @Autowired
    private ISStandardListService standardListService;

    @Autowired
    private ISProfilesService profilesService;

    @Autowired
    private ISStashListService stashListService;

    @Autowired
    private ISWorkitemSupplementService supplementService;

    @Autowired
    private ISRollbackService rollbackService;

    @Autowired
    private ISRepealService repealService;

    @Autowired
    private ISRollbackListService rollbackListService;

    @Autowired
    private ISRepealListService repealListService;

    private Map<String, SWorkitem> workitems = new HashMap<>();

    @Override
    public Integer add(WorkitemAddAndUpdateRequest request) {

        SWorkitem workitem = new SWorkitem();
        BeanUtils.copyProperties(request, workitem);
        String lable = "";
        if(request.getItemLable().size() > 0){
            for(String itemLable:request.getItemLable()){
                if("".equals(lable)){
                    lable = itemLable;
                }else{
                    lable = lable + "," + itemLable;
                }
            }
        }
        if(StringUtil.isBlank(lable)){
            workitem.setItemLable(null);
        }else{
            workitem.setItemLable(lable);
        }
        workitem.setItemStatus(ItemStatus.DEVELOP);
        insert(workitem);
        SWorkitemSupplement workitemSupplement = new SWorkitemSupplement();
        BeanUtils.copyProperties(request, workitemSupplement);
        workitemSupplement.setGuid(null);
        workitemSupplement.setGuidWorkitem(workitem.getGuid());
        supplementService.insert(workitemSupplement);
        return workitem.getGuid();
    }

    @Override
    public Integer update(WorkitemAddAndUpdateRequest request) {

        SWorkitem sWorkitem = new SWorkitem();
        BeanUtils.copyProperties(request, sWorkitem);
        String lable = "";
        for(String itemLable:request.getItemLable()){
            if("".equals(lable)){
                lable = itemLable;
            }else{
                lable = lable + "," + itemLable;
            }
        }
        if(StringUtil.isBlank(lable)){
            sWorkitem.setItemLable(null);
        }else{
            sWorkitem.setItemLable(lable);
        }
        if(request.getGuidSupplement() != null){
            SWorkitemSupplement workitemSupplement = new SWorkitemSupplement();
            BeanUtils.copyProperties(request, workitemSupplement);
            workitemSupplement.setGuid(request.getGuidSupplement());
            supplementService.updateById(workitemSupplement);
        }
        updateById(sWorkitem);

        return sWorkitem.getGuid();
    }

    @Override
    public List<SWorkitem> selectWorkitemByUser(String userId) {

        EntityWrapper<SWorkitem> sWorkitemEntityWrapper = new EntityWrapper<>();
        sWorkitemEntityWrapper.eq(SWorkitem.COLUMN_OWNER,userId);
        sWorkitemEntityWrapper.eq(SWorkitem.COLUMN_ITEM_STATUS,ItemStatus.DEVELOP);
        List<SWorkitem> swList = selectList(sWorkitemEntityWrapper);
        return swList;
    }

    @Override
    public SWorkitem selectOneById(Integer workitemId) {

        SWorkitem workitem = this.workitems.get(workitemId);
        if(workitem != null){
            return workitem;
        }
        workitem = selectById(workitemId);
        this.workitems.put(workitem.getGuid().toString(),workitem);
        return workitem;
    }

    @Override
    public void workitemRelevanceBranch(Integer guidWorkitem, Integer guidBranch) {

        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_BRANCH,guidBranch);
        List<SBranchMapping> sBranchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sBranchMappings.size() > 0){
            throw new DeveloperException("此分支已被指配，请重新选择分支！");
        }

        EntityWrapper<SBranchMapping> branchMappingEntityWrapper2 = new EntityWrapper<>();
        branchMappingEntityWrapper2.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,guidWorkitem);
        branchMappingEntityWrapper2.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        List<SBranchMapping> sBranchMappings2 = branchMappingService.selectList(branchMappingEntityWrapper2);
        if(sBranchMappings2.size() > 0){
            throw new DeveloperException("此工作项已关联分支！");
        }

        SBranchMapping branchMapping = new SBranchMapping();
        branchMapping.setGuidBranch(guidBranch);
        branchMapping.setForWhat(BranchForWhat.WORKITEM);
        branchMapping.setGuidOfWhats(guidWorkitem);
        branchMapping.setAllotTime(new Date());
        branchMapping.setStatus(BranchMappingStatus.TAKE);
        branchMappingService.insert(branchMapping);
    }

    @Override
    public void workitemCancelBranch(Integer guidWorkitem) {
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,guidWorkitem);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        List<SBranchMapping> sbmList = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sbmList.size() != 1){
            throw new DeveloperException("此工作项没有关联分支！");
        }

        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,guidWorkitem);
        deliveryEntityWrapper.eq(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.APPLYING);
        if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项关联的分支有投放申请，不允许取消关联！");
        }

        SBranchMapping branchMapping = sbmList.get(0);
        branchMappingService.deleteById(branchMapping.getGuid());
    }

    @Override
    public SBranch selectBranchByWorkitemGuid(Integer workitemGuid) {
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,workitemGuid);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() != 1){
            throw new DeveloperException("此工作项没有分配分支信息！");
        }
        SBranchMapping branchMapping = branchMappings.get(0);
        return branchService.selectById(branchMapping.getGuidBranch());
    }

    @Override
    public List<SBranch> mayRelevanceBranch() {

        List<SBranchMapping> sBranchMappings = branchMappingService.selectList(null);
        List<Integer> branchGuid = new ArrayList<>();
        if(sBranchMappings.size() > 0){
            for (SBranchMapping branchMapping:sBranchMappings){
                branchGuid.add(branchMapping.getGuidBranch());
            }
            if(branchGuid.size() == 0){
                throw new DeveloperException("没有查询到未被指配的分支");
            }
        }
        EntityWrapper<SBranch> branchEntityWrapper = new EntityWrapper<>();
        branchEntityWrapper.notIn(SBranch.COLUMN_GUID,branchGuid);
        branchEntityWrapper.ne(SBranch.COLUMN_BRANCH_TYPE,BranchType.RELEASE);
        return branchService.selectList(branchEntityWrapper);
    }

    @Override
    public Page<WorkitemBranchDetail> workitemFullPathDetail(Page<WorkitemBranchDetail> page,
                                                             EntityWrapper<WorkitemBranchDetail> wrapper) {
        List<WorkitemBranchDetail> workitemBranchDetailPage = this.baseMapper.selectWorkitemDetail(page, wrapper);
        for(WorkitemBranchDetail workitemBranchDetail:workitemBranchDetailPage){
            if(workitemBranchDetail.getItemLable() == null){
                workitemBranchDetail.setItemLables(new ArrayList<>());
            }else{
                String[] itemLables = workitemBranchDetail.getItemLable().split(",");
                workitemBranchDetail.setItemLables(Arrays.asList(itemLables));
            }

        }
        return page.setRecords(workitemBranchDetailPage);
    }

    @Override
    public void updateStatusCancel(Integer guidWorkitem) {
        SWorkitem sWorkitem = selectById(guidWorkitem);
        if(sWorkitem == null){
            throw new DeveloperException("此工作项不存在或已被删除！");
        }
        if(sWorkitem.getItemStatus().equals(ItemStatus.CANCEL)){
            throw new DeveloperException("此工作项被已关闭！");
        }
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.notIn(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.doneResult());
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,sWorkitem.getGuid());
        if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项有投放申请未完成操作，不能关闭！");
        }

        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, sWorkitem.getGuid())
                            .eq(SRepeal.COLUMN_REPEAL_STATUS, RepealStatus.MODIFIED);
        if(repealService.selectList(repealEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项有延期申请未完成操作，不能关闭！");
        }
        EntityWrapper<SRollback> rollbackEntityWrapper = new EntityWrapper<>();
        rollbackEntityWrapper.eq(SRollback.COLUMN_GUID_WORKITEM, sWorkitem.getGuid())
                .eq(SRollback.COLUMN_ROLLBACK_STATUS, RollbackStatus.UNDERWAY);
        if(rollbackService.selectList(rollbackEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项有回退申请未完成操作，不能关闭！");
        }

        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,sWorkitem.getGuid());
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        if(branchMappingService.selectList(branchMappingEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项有关联的分支，不能关闭！");
        }
        sWorkitem.setItemStatus(ItemStatus.CANCEL);
        sWorkitem.setCloseTime(new Date());
        updateById(sWorkitem);
    }

    @Override
    public void updateStatusPutProduct(Integer guidWorkitem) throws ParseException {
        SWorkitem sWorkitem = selectById(guidWorkitem);

        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.notIn(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.doneResult());
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,sWorkitem.getGuid());
        if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
            throw new DeveloperException("此工作项有投放申请未完成操作，不能投产！");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        sWorkitem.setItemStatus(ItemStatus.STARTUP);
        sWorkitem.setDeliveryTime(format.parse(format.format(new Date())));
        updateById(sWorkitem);
    }

    @Override
    public void insertBranch(Integer guid, SBranch branch) throws SVNException {
        SWorkitem sWorkitem = selectById(guid);
        if (sWorkitem == null) {
            throw new DeveloperException(guid + "对应工作项已删除或不存在！");
        }
        EntityWrapper<SBranch> branchEntityWrapper = new EntityWrapper<>();
        branchEntityWrapper.eq(SBranch.COLUMN_FULL_PATH, branch.getFullPath());
        List<SBranch> branches = branchService.selectList(branchEntityWrapper);
        if(branches.size() > 0){
            throw new DeveloperException("该分支路径已存在，请重新填写！");
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper
                .eq(SBranchMapping.COLUMN_GUID_OF_WHATS, guid)
                .eq(SBranchMapping.COLUMN_FOR_WHAT, branch.getBranchType());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if (!CollectionUtils.isEmpty(branchMappings)) {
            throw new DeveloperException("该工作项已经关联分支，不能重复添加！");
        }
        String message = String.format("[artf%s]:建分支", sWorkitem.getArtf());
        String fullPath = (branch.getBranchType().equals(BranchType.FEATURE) ? svnProperties.getBaseFeatureUrl()
                : svnProperties.getBaseHotfixUrl()) + new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        branch.setFullPath(fullPath);
        long revision = svnKitService.doMkDir(branch.getFullPath(), message);
        try {
            branch.setCurrVersion((int) revision);
            branch.setLastVersion((int) revision);
            branchService.insert(branch);
            SBranchMapping sBranchMapping = new SBranchMapping();
            sBranchMapping.setAllotTime(new Date());
            sBranchMapping.setForWhat(BranchForWhat.WORKITEM);
            sBranchMapping.setStatus(BranchMappingStatus.TAKE);
            sBranchMapping.setGuidBranch(branch.getGuid());
            sBranchMapping.setGuidOfWhats(Integer.valueOf(guid));
            branchMappingService.insert(sBranchMapping);
        } catch (Exception e) {
            svnKitService.doDelete(branch.getFullPath(), message + "异常回滚！");
            throw e;
        }
    }

    @Override
    public void insertProjects(String guid, List<String> projectGuids) throws SVNException {
        SWorkitem sWorkitem = selectById(guid);
        if (sWorkitem == null) {
            throw new DeveloperException(guid + "对应工作项已删除或不存在！");
        }
        List<Map> maps = branchService.selectListByForWhatIds(BranchForWhat.WORKITEM, Collections.singletonList(guid));
        if (CollectionUtils.isEmpty(maps)) {
            throw new DeveloperException(guid + "对应工作项没有关联分支");
        }
        String destUrl = maps.get(0).get("fullPath").toString();
        EntityWrapper<SProject> wrapper = new EntityWrapper<>();
        wrapper.in(SProject.COLUMN_GUID, projectGuids);
        List<SProject> sProjects = projectService.selectList(wrapper);
        String[] sourceUrls = new String[sProjects.size()];
        for (int i = 0; i < sProjects.size(); i++) {
            if (!projectGuids.contains(sProjects.get(i).getGuid().toString())) {
                throw new DeveloperException(guid + "对应工程已删除或不存在！");
            }
            sourceUrls[i] = sProjects.get(i).getFullPath();
        }
        String message = String.format("[artf%s]:拉工程", sWorkitem.getArtf());
        svnKitService.doCopy(sourceUrls, destUrl, message);
    }

    @Override
    public ProjectDetail selectProjects(Integer guid) throws SVNException {
        SWorkitem sWorkitem = selectById(guid);
        if (sWorkitem == null) {
            throw new DeveloperException(guid + "对应工作项已删除或不存在！");
        }
        List<Map> maps = branchService.selectListByForWhatIds(BranchForWhat.WORKITEM, Collections.singletonList(guid));
        if (CollectionUtils.isEmpty(maps)) {
            throw new DeveloperException(guid + "对应工作项没有关联分支");
        }
        List<String> dir = svnKitService.getDir(maps.get(0).get("fullPath").toString());
        List<SProject> sProjects = projectService.selectProjectAll();
        Map<Boolean, List<SProject>> collect = sProjects.stream()
                .collect(Collectors.groupingBy(p -> dir.contains(p.getProjectName())));
        ProjectDetail projectDetail = new ProjectDetail();
        projectDetail.setOwn(collect.get(true) != null ? collect.get(true) : Collections.EMPTY_LIST);
        projectDetail.setOthers(collect.get(false) != null ? collect.get(false) : Collections.EMPTY_LIST);
        return projectDetail;
    }

    @Override
    public boolean selectStandardListByGuid(Integer guidWorkitem) {
        EntityWrapper<SStandardList> standardListEntityWrapper = new EntityWrapper<>();
        standardListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, guidWorkitem);
        List<SStandardList> standardLists = standardListService.selectList(standardListEntityWrapper);
        if(standardLists.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public WorkitemGeneralDetail selectWorkitemGeneral(Integer guidWorkitem) {
        WorkitemGeneralDetail workitemGeneralDetail = new WorkitemGeneralDetail();
        SWorkitem workitem = selectById(guidWorkitem);
        if(workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        EntityWrapper<SWorkitemSupplement> supplementEntityWrapper = new EntityWrapper<>();
        supplementEntityWrapper.eq(SWorkitemSupplement.COLUMN_GUID_WORKITEM, workitem.getGuid());
        List<SWorkitemSupplement> workitemSupplements = supplementService.selectList(supplementEntityWrapper);

        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,workitem.getGuid());
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() > 0){
            SBranchMapping branchMapping = branchMappings.get(0);
            workitemGeneralDetail.setBranch(branchService.selectById(branchMapping.getGuidBranch()));
        }

        workitemGeneralDetail.setWorkitem(workitem);
        if(workitemSupplements.size() > 0){
            workitemGeneralDetail.setWorkitemSupplement(workitemSupplements.get(0));
        }
        workitemGeneralDetail.setWorkitemSupplement(null);
        workitemGeneralDetail.setProfiles(selectPutProfiles(workitem.getGuid()));
        workitemGeneralDetail.setLifecycle(selectWorkitemLifecycle(workitem));
        workitemGeneralDetail.setDeliverdCount(selectDeliverdCount(workitem.getGuid()));
        workitemGeneralDetail.setStandardCount(selectStandardCount(workitem.getGuid()));
        return workitemGeneralDetail;
    }

    @Override
    public List<DeliveryProjectDetail> selectStandardListDetailByGuid(Integer guidWorkitem) {
        List<SStandardList> standardLists = selectStandardList(guidWorkitem);
        return DeliveryProjectDetail.getStandardDetail(standardLists, projectService.selectProjectAll());
    }

    @Override
    public List<DeliveryProjectDetail> selectStashListDetailByGuid(Integer guidWorkitem) {
        SWorkitem workitem = selectById(guidWorkitem);
        if(workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        EntityWrapper<SStashList> standardListEntityWrapper = new EntityWrapper<>();
        standardListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, workitem.getGuid());
        List<SStashList> sStashLists = stashListService.selectList(standardListEntityWrapper);
        return DeliveryProjectDetail.getStashDetail(sStashLists, projectService.selectProjectAll());
    }

    @Override
    public List<SStandardList> exportStandardList(Integer guidWorkitem) {
        SWorkitem workitem = selectById(guidWorkitem);
        if(workitem == null){
            throw new DeveloperException("找不到此guid"+guidWorkitem+"对应的工作项！");
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.WORKITEM);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS, workitem.getGuid());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() == 0){
            throw new DeveloperException("此工作项"+workitem.getItemName()+"没有对应的分支信息！");
        }
        SBranch branch = branchService.selectById(branchMappings.get(0).getGuidBranch());

        EntityWrapper<SStandardList> standardListEntityWrapper = new EntityWrapper<>();
        standardListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, guidWorkitem);
        standardListEntityWrapper.ne(SStandardList.COLUMN_COMMIT_TYPE,CommitType.DELETED.getValue().toString());
        List<SStandardList> standardLists = standardListService.selectList(standardListEntityWrapper);
        if(standardLists.size() == 0){
            throw new DeveloperException("此工作项"+workitem.getItemName()+"没有成功投放的代码！");
        }
        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, guidWorkitem)
                            .eq(SRepeal.COLUMN_REPEAL_STATUS, RepealStatus.DELETED);
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);
        if (repeals.size() > 0){
            //获取延期申请的guid集合
            List<Integer> guids = repeals.stream().map(SRepeal::getGuid).collect(Collectors.toList());

            EntityWrapper<SRepealList> repealListEntityWrapper = new EntityWrapper<>();
            repealListEntityWrapper.in(SRepealList.COLUMN_GUID_REPEAL, guids)
                    .eq(SRepealList.COLUMN_DELIVERY_STATUS, DeliveryStatus.NOTLAUNCH);
            List<SRepealList> repealLists = repealListService.selectList(repealListEntityWrapper);

            if(repealLists.size() > 0){
                //获取已确定延期但未投放的代码集合
                List<String> fullPaths = repealLists.stream().map(SRepealList::getFullPath).collect(Collectors.toList());

                standardLists = standardLists.stream().filter(sStandardList ->
                        !fullPaths.contains(sStandardList.getFullPath())).collect(Collectors.toList());
            }
        }
        return disposeExportExcel(standardLists, branch.getFullPath());
    }

    @Override
    public List<String> selectLableAll(String lable) {
        List<SWorkitem> workitems = selectList(null);

        Set<String> strings = new HashSet<>();
        for (SWorkitem workitem: workitems){
            if(StringUtil.isBlank(workitem.getItemLable())){
                continue;
            }
            String[] itemLable = workitem.getItemLable().split(",");
            for (String lab:itemLable){
                if(StringUtil.isBlank(lable)){
                    strings.add(lab);
                }else if(lab.contains(lable)){
                    strings.add(lab);
                }
            }
        }
        return new ArrayList<>(strings);
    }

    @Override
    public boolean verifyArtf(VerifyArtfRequest request) {
        List<SWorkitem> workitems = null;
        if("A".equals(request.getType())){
            workitems = selectList(null);
        }else if("U".equals(request.getType())){
            EntityWrapper<SWorkitem> workitemEntityWrapper = new EntityWrapper<>();
            workitemEntityWrapper.ne(SWorkitem.COLUMN_GUID ,request.getGuidWorkitem());
            workitems = selectList(workitemEntityWrapper);
        }else{
            throw new DeveloperException("此"+request.getType()+"类型不存在！");
        }
        for(SWorkitem workitem:workitems){
            if(workitem.getArtf() != null){
                if(workitem.getArtf().equals(request.getArtf())){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public HomepageShowDetail selectHomepageShow() {

        HomepageShowDetail homepageShowDetail = new HomepageShowDetail();
        homepageShowDetail.setDeliveryResultGroupCount(deliveryService.selectDeliveryResultGroupCount());
        homepageShowDetail.setProfilesCount( profilesService.selectCount(null));
        homepageShowDetail.setWorkTypeStatusGroupCount(selectWorkTypeStatusGroupCount());
        homepageShowDetail.setDeliveryCount(deliveryService.selectCount(null));
        homepageShowDetail.setWorkitemCount(selectCount(null));
        homepageShowDetail.setDeliveryProfilesDetails(profilesService.selectProfilesDeliveryCount());
        return homepageShowDetail;
    }

    /**
     *
     * 主页重点追踪需求
     */
    @Override
    public List<WorkitemProfilesNameDetail> selectWorkitemProfilesDetail(HomePageShowEmphasisRequest request){

        SimpleDateFormat format = new SimpleDateFormat("M月");
        String time = format.format(new Date());
        request.getItemLables().add(time);

        List<WorkitemProfilesNameDetail> details = this.baseMapper.selectWorkitemProfilesDetail(request.getItemLables(),
                request.getWorkType(),request.getBeginTime(),request.getEndTime());
        List<WorkitemProfilesNameDetail> workitemProfilesNameDetails = new ArrayList<>();
        details.stream().collect(Collectors.groupingBy(WorkitemProfilesNameDetail::getGuid)).forEach((guid, detailList) ->{
            WorkitemProfilesNameDetail profilesNameDetail = new WorkitemProfilesNameDetail();
            profilesNameDetail.setGuid(detailList.get(0).getGuid());
            profilesNameDetail.setDeliveryTime(detailList.get(0).getDeliveryTime());
            profilesNameDetail.setItemName(detailList.get(0).getItemName());
            profilesNameDetail.setOwner(detailList.get(0).getOwner());
            profilesNameDetail.setItemLable(detailList.get(0).getItemLable());
            List<String> profilse = new ArrayList<>();
            detailList.forEach(data ->{
                if(!StringUtil.isBlank(data.getProfilesName())){
                    profilse.add(data.getProfilesName());
                }
            });
            profilesNameDetail.setProfilseNames(profilse);
            workitemProfilesNameDetails.add(profilesNameDetail);
        });
        return workitemProfilesNameDetails;
    }

    @Override
    public Page<SStandardList> selectStandardListAll(Integer guidWorkitem, Page<SStandardList> page,
                                                     EntityWrapper<SStandardList> wrapper) {
        SWorkitem workitem = selectById(guidWorkitem);
        if (workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        wrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, guidWorkitem);

        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, guidWorkitem);
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);
        if (repeals.size() > 0){
            List<Integer> guidRepeals = repeals.stream().map(SRepeal::getGuid).collect(Collectors.toList());
            EntityWrapper<SRepealList> repealListEntityWrapper = new EntityWrapper<>();
            repealListEntityWrapper.in(SRepealList.COLUMN_GUID_REPEAL, guidRepeals);
            repealListEntityWrapper.eq(SRepealList.COLUMN_DELIVERY_STATUS, DeliveryStatus.NOTLAUNCH);
            List<SRepealList> repealLists = repealListService.selectList(repealListEntityWrapper);

            if (repealLists.size() > 0){
                List<String> fullPaths = repealLists.stream().map(SRepealList::getFullPath).collect(Collectors.toList());

                wrapper.notIn(SStandardList.COLUMN_FULL_PATH, fullPaths);
                Page<SStandardList> sStandardLists = standardListService.selectPage(page, wrapper);
                return sStandardLists;
            }
        }
        Page<SStandardList> standardLists = standardListService.selectPage(page, wrapper);
        return standardLists;
    }

    @Override
    public void createRollback(String userId, RollBackAddRequest request) {
        SWorkitem workitem = selectById(request.getGuidWorkitem());
        if(workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        if(workitem.getItemStatus().equals(ItemStatus.CANCEL) ||
                workitem.getItemStatus().equals(ItemStatus.STARTUP)){
            throw new DeveloperException("已投产或已取消的工作项不允许回退代码！");
        }
        EntityWrapper<SRollback> rollbackEntityWrapper = new EntityWrapper<>();
        rollbackEntityWrapper.eq(SRollback.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        rollbackEntityWrapper.eq(SRollback.COLUMN_ROLLBACK_STATUS, RollbackStatus.UNDERWAY);
        List<SRollback> rollbacks = rollbackService.selectList(rollbackEntityWrapper);
        if (rollbacks.size() > 0){
            throw new DeveloperException("此工作项已有回退申请正在回退中，请完成后再操作！");
        }

        List<String> deilveryResults = new ArrayList<>();
        deilveryResults.add(DeliveryResult.FAILED.getValue().toString());
        deilveryResults.add(DeliveryResult.DELIVERED.getValue().toString());
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        deliveryEntityWrapper.notIn(SDelivery.COLUMN_DELIVERY_RESULT, deilveryResults);
        List<SDelivery> deliveries = deliveryService.selectList(deliveryEntityWrapper);
        if (deliveries.size() > 0){
            throw new DeveloperException("此工作项有投放申请在申请中或正在处理中，不允许回退！");
        }

        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        repealEntityWrapper.eq(SRepeal.COLUMN_REPEAL_STATUS, RepealStatus.MODIFIED);
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);
        if (repeals.size() > 0){
            throw new DeveloperException("此工作项有撤销申请正在撤销中，请处理完成后再回退！");
        }

        List<SStandardList> standardLists = standardListService.selectBatchIds(request.getGuidStandarLists());
        if (standardLists.size() != request.getGuidStandarLists().size()){
            throw new DeveloperException("有代码文件已回退，请重新操作！");
        }
        //新增回退申请
        SRollback rollback = new SRollback();
        rollback.setGuidWorkitem(request.getGuidWorkitem());
        rollback.setApplyPerson(userId);
        rollback.setRollbackDesc(request.getRollbackDesc());
        rollback.setRollbackTime(new Date());
        rollback.setRollbackStatus(RollbackStatus.UNDERWAY);
        rollbackService.insert(rollback);

        List<SRollbackList> rollbackLists = new ArrayList<>();
        for (SStandardList standardList:standardLists){
            SRollbackList rollbackList = new SRollbackList();
            BeanUtils.copyProperties(standardList,rollbackList);
            rollbackList.setGuid(null);
            rollbackList.setGuidRollback(rollback.getGuid());
            rollbackLists.add(rollbackList);
        }
        rollbackListService.insertBatch(rollbackLists);
    }

    @Override
    public List<SRollback> selectRollbackByGuidWorkitem(Integer guidWorkitem) {
        EntityWrapper<SRollback> rollbackEntityWrapper = new EntityWrapper<>();
        rollbackEntityWrapper.eq(SRollback.COLUMN_GUID_WORKITEM, guidWorkitem);
        List<SRollback> rollbacks = rollbackService.selectList(rollbackEntityWrapper);
        if (rollbacks.size() == 0){
            return new ArrayList<>();
        }
        return rollbacks;
    }

    @Override
    public List<DeliveryProjectDetail> selectRollbackListByGuid(Integer guidRollback) {
        EntityWrapper<SRollbackList> rollbackListEntityWrapper = new EntityWrapper<>();
        rollbackListEntityWrapper.eq(SRollbackList.COLUMN_GUID_ROLLBACK, guidRollback);
        List<SRollbackList> rollbackLists = rollbackListService.selectList(rollbackListEntityWrapper);
        if (rollbackLists.size() == 0){
            return null;
        }
        return DeliveryProjectDetail.getRollbackDetail(rollbackLists, projectService.selectList(null));
    }

    @Override
    public List<SRepeal> selectRepealAll(Integer guidWorkitem) {
        SWorkitem workitem = selectById(guidWorkitem);
        if (workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, guidWorkitem);
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);
        if(repeals.size() == 0){
            return new ArrayList<>();
        }
        return repeals;
    }


    /**
     * 查询工作项的标准清单代码
     * @param guidWorkitem
     * @return
     */
    public List<SStandardList> selectStandardList(Integer guidWorkitem){
        SWorkitem workitem = selectById(guidWorkitem);
        if (workitem == null){
            throw new DeveloperException("对应工作项信息不存在！");
        }
        EntityWrapper<SStandardList> standardListEntityWrapper = new EntityWrapper<>();
        standardListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, workitem.getGuid());
        List<SStandardList> standardLists = standardListService.selectList(standardListEntityWrapper);
        return standardLists;
    }

    /**
     * 查询工作项投放成功过的环境
     * @param guidWorkitem
     * @return
     */
    public List<SProfiles> selectPutProfiles(Integer guidWorkitem) {
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, guidWorkitem);
        deliveryEntityWrapper.eq(SDelivery.COLUMN_DELIVERY_RESULT, DeliveryResult.DELIVERED);
        deliveryEntityWrapper.groupBy(SDelivery.COLUMN_GUID_PROFILES);
        List<SDelivery> deliveries = deliveryService.selectList(deliveryEntityWrapper);
        if (deliveries.size() > 0){
            List<Integer> profiles = deliveries.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());
            return profilesService.selectBatchIds(profiles);
        }
        return null;
    }

    /**
     * 工作项的生命周期
     * @param workitem
     */
    public List<Map<String,Object>> selectWorkitemLifecycle(SWorkitem workitem){

        //查询某个环境交付成功投放申请集合
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, workitem.getGuid());
        deliveryEntityWrapper.eq(SDelivery.COLUMN_DELIVERY_RESULT, DeliveryResult.DELIVERED);
        deliveryEntityWrapper.groupBy(SDelivery.COLUMN_GUID_PROFILES);
        deliveryEntityWrapper.orderBy(SDelivery.COLUMN_DELIVERY_TIME);
        List<SDelivery> deliveries = deliveryService.selectList(deliveryEntityWrapper);

        Map<Integer,SProfiles> delivered = null;
        if(deliveries.size() > 0){
            List<Integer> profiels = deliveries.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());
            delivered = profilesService.selectBatchIds(profiels).stream().
                    collect(Collectors.toMap(SProfiles::getGuid, p -> p));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //获取此工作项所有投放申请信息
        EntityWrapper<SDelivery> sDeliveryEntityWrapper = new EntityWrapper<>();
        sDeliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, workitem.getGuid());
        sDeliveryEntityWrapper.orderBy(SDelivery.COLUMN_APPLY_TIME,true);
        List<SDelivery> sDeliveries = deliveryService.selectList(sDeliveryEntityWrapper);

        Map<Integer,SProfiles> exploit = null;
        if(sDeliveries.size() > 0){
            List<Integer> profiels = sDeliveries.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());
            exploit = profilesService.selectBatchIds(profiels).stream().
                    collect(Collectors.toMap(SProfiles::getGuid, p -> p));
        }
        //组装生命周期
        WorkitemLifecycle[] lifecycle = WorkitemLifecycle.values();
        List<Map<String,Object>> lifecList = new ArrayList<>();
        //组装工作项生命周期
        for (WorkitemLifecycle life:lifecycle){
            Map<String,Object> map = new HashMap<>();
            map.put("step",life);
            if(life.equals(WorkitemLifecycle.CREATE)){
                map.put("time",workitem.getReceiveTime());
                map.put("status",IsIllume.ILLUME);
                lifecList.add(map);
                continue;
            } else if(life.equals(WorkitemLifecycle.CLOSE)){
                if(workitem.getItemStatus().equals(ItemStatus.CANCEL)){
                    map.put("time",workitem.getCloseTime());
                    map.put("status",IsIllume.ILLUME);
                    lifecList.add(map);
                    continue;
                }
            }else if(life.equals(WorkitemLifecycle.EXPLOIT)){
                List<Map<String,Object>> deliveryList = new ArrayList<>();
                if(exploit != null){
                    for (SDelivery delivery:sDeliveries){
                        Map<String,Object> deliveryMap = new HashMap<>();
                        SProfiles profiles = exploit.get(delivery.getGuidProfiles());
                        deliveryMap.put("profilesName",profiles.getProfilesName());
                        deliveryMap.put("time",simpleDateFormat.format(delivery.getApplyTime()));
                        deliveryMap.put("deliver",delivery.getDeliver());
                        deliveryList.add(deliveryMap);
                    }
                    map.put("profiles",deliveryList);
                    map.put("status",IsIllume.ILLUME);
                    lifecList.add(map);
                    continue;
                }
                map.put("profiles",deliveryList);
                map.put("status",IsIllume.NO_ILLUME);
                lifecList.add(map);
                continue;
            }else{
                List<Map<String,Object>> deliveryList = new ArrayList<>();
                if(delivered != null){
                    for (SDelivery sDelivery:deliveries){
                        Map<String,Object> deliveryMap = new HashMap<>();
                        SProfiles profiles = delivered.get(sDelivery.getGuidProfiles());
                        deliveryMap.put("profilesName",profiles.getProfilesName());
                        deliveryMap.put("time",simpleDateFormat.format(sDelivery.getDeliveryTime()));
                        deliveryMap.put("deliver",sDelivery.getDeliver());
                        deliveryList.add(deliveryMap);
                    }
                    map.put("profiles",deliveryList);
                    map.put("status",IsIllume.ILLUME);
                    lifecList.add(map);
                    continue;
                }
                map.put("profiles",deliveryList);
                map.put("status",IsIllume.NO_ILLUME);
                lifecList.add(map);
                continue;
            }
            map.put("time","");
            map.put("status",IsIllume.NO_ILLUME);
            lifecList.add(map);
        }
        return lifecList;
    }

    /**
     * 统计工作项的提申请数量
     * @param workitemGuid
     * @return
     */
    public int selectDeliverdCount(Integer workitemGuid){

        return this.baseMapper.selectWorkitemDeliverdCount(workitemGuid);
    }

    /**
     * 统计工作项的代码变动数量
     * @param workitemGuid
     * @return
     */
    public int selectStandardCount(Integer workitemGuid){

        return this.baseMapper.selectStandardCount(workitemGuid);
    }

    /**
     * 标准清单将需要导出的代码清单进行整理
     * @param sdlList
     * @param branchPath
     * @return
     */
    public List<SStandardList> disposeExportExcel(List<SStandardList> sdlList, String branchPath){
        List<SStandardList> standardLists = new ArrayList<>();

        sdlList.stream().collect(Collectors.groupingBy(SStandardList::getPatchType)).forEach((p, list) -> {
            if (p.equals(PatchType.ECD.getValue())) {
                list.stream().collect(Collectors.groupingBy(SStandardList::getPartOfProject,
                        Collectors.groupingBy(dl -> DeveloperUtils.getModule(dl.getFullPath(), branchPath))))
                        .forEach((pj, m) -> m.forEach((module, l) -> {
                            // 导出ecd 的同工程清单
                            JSONObject jsonObject = JSONObject.parseObject(l.get(0).getDeployWhere());
                            String [] deployWhereSplit = jsonObject.getString(l.get(0).getPatchType()).split(",");

                            for (String deployWhere : deployWhereSplit) {
                                SStandardList standardList = new SStandardList();
                                standardList.setPatchType(l.get(0).getPatchType());
                                standardList.setDeployWhere(deployWhere);
                                standardList.setPartOfProject(pj);
                                standardList.setFullPath(DeveloperUtils.getEcdPath(l.get(0).getFullPath(), pj));
                                standardLists.add(standardList);
                            }
                        }));
            } else {
                for (SStandardList sd : list) {
                    JSONObject jsonObject = JSONObject.parseObject(sd.getDeployWhere());
                    String[] patchTypeSplit = sd.getPatchType().split(",");
                    for (String patchType : patchTypeSplit) {
                        String deployWhere = jsonObject.getString(patchType);
                        String[] deployWhereSplit = deployWhere.split(",");
                        for (String dw : deployWhereSplit) {
                            SStandardList standardList = new SStandardList();
                            standardList.setPatchType(patchType);
                            standardList.setDeployWhere(dw);
                            standardList.setPartOfProject(sd.getPartOfProject());
                            standardList.setFullPath(sd.getFullPath());
                            standardLists.add(standardList);
                        }
                    }

                }
            }
        });
        return standardLists;
    }

    /**
     * 查询工作项按工作项类型及状态分组统计
     */
    public List<Map<String, String>> selectWorkTypeStatusGroupCount(){
        List<DeliveryResultCountDetail> countDetailList = this.baseMapper.selectWorkTypeStatusGroupCount();

        /*for (WorkType workType:WorkType.values()){
            here:
            for(ItemStatus itemStatus:ItemStatus.values()){
                for (DeliveryResultCountDetail detail:countDetailList){
                    if(workType.getValue().equals(detail.getWorkType().getValue()) &&
                            itemStatus.getValue()==detail.getItemStatus().getValue()){
                        continue here;
                    }
                }
                DeliveryResultCountDetail resultCountDetail = new DeliveryResultCountDetail();
                resultCountDetail.setCount(0);
                resultCountDetail.setWorkType(workType);
                resultCountDetail.setItemStatus(itemStatus);
                countDetailList.add(resultCountDetail);
            }
        }*/

        List<Map<String, String>> deliveredDetail = new ArrayList<>();
        for (WorkType workType:WorkType.values()){
            Map<String, String> map = new HashMap<>();
            map.put("workType", workType.getValue().toString());
            //here: 跳转循环标识,查询到数据有此类型以及一致的，添加后跳出到指定循环
            here:
            for(ItemStatus itemStatus:ItemStatus.values()){
                if (countDetailList.size() > 0){
                    for (DeliveryResultCountDetail detail:countDetailList){
                        if(workType.getValue().equals(detail.getWorkType().getValue()) &&
                                itemStatus.getValue()==detail.getItemStatus().getValue()){
                            map.put(itemStatus.getValue().toString(), String.valueOf(detail.getCount()));
                            continue here;
                        }
                    }
                }
                map.put(itemStatus.getValue().toString(), "0");
            }
            deliveredDetail.add(map);
        }
        return deliveredDetail;
    }



}

